<?php
namespace App\Http\Controllers\Api\Buz;

use App\Http\Controllers\Controller;
use App\Lib\Code;
use App\Models\ProvinceCity;
use App\Repositories\Criteria\AuthUserCriteria;
use App\Repositories\Criteria\RemitSettingCriteria;
use App\Repositories\Criteria\TimeFilterCriteria;
use App\Repositories\Criteria\ToPayCriteria;
use App\Repositories\Eloquent\AssetCountEloquent;
use App\Repositories\Eloquent\PlatSettingRepository;
use App\Repositories\Eloquent\ToPayOrderRepository;
use App\Services\ApiResponseService;
use App\Services\RemitOrderService;
use App\Validators\Buz\ToPayOrderValidator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use function Sodium\compare;

class ToPayOrderController extends Controller
{
    protected $orderRepository;
    protected $settingRepository;
    protected $setting;

    public function __construct(ToPayOrderRepository $toPayOrderRepository,
                                PlatSettingRepository $platSettingRepository)
    {
        $this->orderRepository = $toPayOrderRepository;
        $this->orderRepository->pushCriteria(AuthUserCriteria::class);
        $this->settingRepository = $platSettingRepository->pushCriteria(RemitSettingCriteria::class);
        $this->setting = $this->settingRepository->first();
    }

    public function index(Request $request)
    {
//        $this->orderRepository->pushCriteria(new TimeFilterCriteria($request));
        $lists = $this->orderRepository
            ->groupBy('batch_no')
            ->with(['manyChild' => function ($query) {
                return $query->select('id', 'plat_no', 'batch_no',
                    'money', 'status', 'disposal', 'fee', 'ac_money',
                    'bk_username', 'bk_category', 'bk_account',
                    'bk_prov', 'bk_city', 'bk_branch',
                    'bk_number', 'remark', 'ad_remark',
                    'updated_at');
            }])
            ->orderBy('created_at', 'desc')
            ->paginate(15, [
            'batch_no', DB::raw('sum(`money`) as total_money'), DB::raw('sum(`fee`) as total_fee'), DB::raw('sum(`ac_money`) as total_ac_money'),
            DB::raw('count(`batch_no`) as num'), 'status', 'created_at'
          ]);
        return ApiResponseService::returnData($lists);

    }

    public function singleStore(Request $request,
                                ToPayOrderValidator $toPayOrderValidator,
                                RemitOrderService $remitOrderService)
    {
        $data = $request->all(array_keys($toPayOrderValidator->getRules('single')));
        $toPayOrderValidator->with($data)->passesOrFail('single');
        $user = Auth::user();
        $asset = $user->assets;
        $setting = $this->setting->value;
        $money = $data['money'];

        //判断是否金额是否达到条件
        $code = $remitOrderService->isPassable($money, $setting);
        if ($code !== true) {
            return ApiResponseService::showError($code);
        }
        $fee = $remitOrderService->remitFee($money, $setting);
        $ac_money = bcadd($money, $fee, 2);
        if (bccomp($asset->available, $ac_money, 2) == -1) {
            return ApiResponseService::showError(Code::BALANCE_INSUFFICIENT);
        }
        $data += compact('ac_money', 'fee');
        $city = ProvinceCity::find($data['city_id']);
        $data['bk_prov'] = $city->province;
        $data['bk_city'] = $city->city;
        array_forget($data, 'city_id');
        $list = [$data];
        $total = [
            'num' => 1,
            'money' => $money,
            'fee' => $fee,
            'ac_money' => $ac_money
        ];
        return ApiResponseService::returnData([compact('total', 'list')]);
    }

    public function batchStore(Request $request,
                               ToPayOrderValidator $toPayOrderValidator,
                               RemitOrderService $remitOrderService)
    {
        $toPayOrderValidator->with($request->all())->passesOrFail('batch');
        $file = $request->file('batch_file');
        $excel_data = [];
        $data = Excel::load($file->getRealPath(), function ($reader) use ( & $excel_data) {
            $reader_arr = $reader->toArray();
            $excel_data = $reader_arr[0];
        });
        $excel_data = array_filter($excel_data);
        $user = Auth::user();
        $asset = $user->assets;
        $setting = $this->setting->value;
        $total = [
            'num' => 0,
            'money' => 0,
            'ac_money' => 0,
            'fee' => 0
        ];
        foreach ($excel_data as & $data) {
            $toPayOrderValidator->with($data)->passesOrFail('reader');
            $data['fee'] = $remitOrderService->remitFee($data['money'], $setting);
            $data['ac_money'] = bcadd($data['fee'], $data['money']);
            $total['num'] += 1;
            $total['money'] = bcadd($data['money'], $total['money'], 2);
            $total['ac_money'] = bcadd($data['ac_money'], $total['ac_money'], 2);
            $total['fee'] = bcadd($data['fee'], $total['fee'], 2);

        }
        if (bccomp($asset->available, $total['ac_money'], 2) == -1) {
            return ApiResponseService::showError(Code::BALANCE_INSUFFICIENT);
        }
        return ApiResponseService::returnData(
            [
                'total' => $total,
                'list' => $excel_data
            ]);
    }
}
